import SitePoolSelector from '@/components/SitePoolSelector';
import request from '@/request';
import { IPoolBasicRangeSearchParams } from '@/request/sheet/typing';
import { formatDate, formatPoolNos } from '@/utils/format';
import { flatRecordRes } from '@/utils/record';
import exportTableToExcel from '@/utils/sheet/exportXlsx';
import { Button, Form, Input, Modal, Popconfirm, Space, Table,DatePicker,message } from 'antd';
import { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import React, { useEffect, useState } from 'react';

const { RangePicker } = DatePicker;

interface ISheetData{
  // 用药日期
  date: string;
  // 上报日期
  reportDate: string;
  // 上报人
  reporter: string;
  // 塘号
  poolNo: string;
  //药物名称
  drug:string;
  // 用药量
  dosage: number;
  // 生产厂家
  manufacturer: string;
}


const MedicationRecord = () => {
  const [showLoading, setShowLoading] = useState(false);
  const [sheetData, setSheetData]: [ISheetData[], any] = useState([]);
  const [modalOpen, setModalOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [dateRange, setDateRange]: [string[], any] = useState([
    // 默认当天前十五天数据
    dayjs().subtract(14, 'day').format('YYYY-MM-DD'),
    dayjs().format('YYYY-MM-DD'),
  ]);
  useEffect(() => {
    setShowLoading(true);
    request.record
      .getMedicationRecordData({ date: dateRange })
      .then((res) => {
        const sheetData: ISheetData[] = [];
        for (let i = 0; i < res.data.length; i++) {
          const item = flatRecordRes(res.data[i]);
          item['key'] = res.data[i].reportBasic.poolNo + '/' + res.data[i].reportBasic.date + i;
          sheetData.push(item);
        }
        sheetData.sort((a, b) => {
          return dayjs(b.date).valueOf() - dayjs(a.date).valueOf(); // 降序排序
        });
        setSheetData(sheetData);
      })
      .finally(() => setShowLoading(false));
  }, []);

  const SearchBar: React.FC = () => {
    const onFinish = (values: IPoolBasicRangeSearchParams) => {
      setShowLoading(true);
      const dateArr = values.dateRange.map((value) => {
        return value.format('YYYY-MM-DD');
      });
      let poolNos: string[] = [];
      if (values.sitePool) poolNos = formatPoolNos(values.sitePool);
      request.record
        .getMedicationRecordData({ poolNos, date: dateArr })
        .then((res) => {
          const sheetData: ISheetData[] = [];
          for (let i = 0; i < res.data.length; i++) {
            const item = flatRecordRes(res.data[i]);
            item['key'] = res.data[i].reportBasic.poolNo + '/' + res.data[i].reportBasic.date + i;
            sheetData.push(item);
          }
          sheetData.sort((a, b) => {
            return dayjs(b.date).valueOf() - dayjs(a.date).valueOf(); // 降序排序
          });
          setSheetData(sheetData);
          setDateRange(dateArr);
        })
        .finally(() => setShowLoading(false));
        // setModalOpen(false);
    };
    // 此处为用药新增记录
    const [form] = Form.useForm();
    function handleCreate() {
      setConfirmLoading(true);
    
      form.validateFields().then((res: {  
        poolNo: string;
        userId:string;
        drug:string;
        dosage: number;
        manufacturer: string;
        date:string;
        }) => {  
        request.record.addMedicationRecordData({ ...res}).then((res) => {
          if (res.status === 200) {
           message.success('新增成功',2);
           // 添加成功后，重新获取数据
        setShowLoading(true);
        request.record
          .getMedicationRecordData({ date: dateRange })
          .then((res) => {
            const sheetData: ISheetData[] = [];
            for (let i = 0; i < res.data.length; i++) {
              const item = flatRecordRes(res.data[i]);
              item['key'] = res.data[i].reportBasic.poolNo + '/' + res.data[i].reportBasic.date + i;
              sheetData.push(item);
            }
            sheetData.sort((a, b) => {
              return dayjs(b.date).valueOf() - dayjs(a.date).valueOf(); // 降序排序
            });
            setSheetData(sheetData);
          })
          .finally(() => setShowLoading(false));
          } else if (res.status === 201) {
            message.error(res.statusText, 2);
          }else{
            message.error('新增失败！', 2);
          }
        });
      });
      setConfirmLoading(false);
      setModalOpen(false);
    }
    //以上为新增用药记录
    return (
      <div>
      <Form name="customized_form_controls" layout="inline" onFinish={onFinish} className="content-box search-bar">
        <SitePoolSelector type="pool" />
        <Form.Item name="dateRange" label="日期" rules={[{ required: true, message: '该项必填' }]}>
          <RangePicker
            disabledDate={(date) => {
              return date && date > dayjs().endOf('day');
            }}
            placeholder={['开始时间', '结束时间']}
          />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            查询
          </Button>
        </Form.Item>
        <Form.Item>
        <Button
          type="primary"
          style={{ backgroundColor: '#18bc69' }}
          onClick={() => exportTableToExcel('medication-record-table', 'medication-record-table')}
        >
          导出
        </Button>
        </Form.Item>
        <Form.Item>
        <Button type="primary" onClick={() => setModalOpen(true)}>
          新增
        </Button>
        </Form.Item>
      </Form>
       <Modal
       title="新增用药记录"
       open={modalOpen}
       onOk={handleCreate}
       confirmLoading={confirmLoading}
       cancelText="取消"
       okText="确认新增"
       onCancel={() => setModalOpen(false)}
     >
       <Form name="addRecord" style={{ padding: '20px' }} form={form}>
         <Form.Item label="塘号" name="poolNo" rules={[{ required: true, message: '塘号为空' }]}>
           <Input placeholder="请输入塘号" allowClear={true} />
         </Form.Item>
         <Form.Item label="上报人" name="userId" rules={[{ required: true, message: '上报人为空' }]}>
           <Input placeholder="请输入用户名" allowClear={true} />
         </Form.Item>
         <Form.Item label="药物名称" name="drug" rules={[{ required: true, message: '药物名称为空' }]}>
           <Input placeholder="请输入药物名称" allowClear={true} />
         </Form.Item>
         <Form.Item label="使用量" name="dosage" rules={[{ required: true, message: '使用量为空' }]}>
           <Input placeholder="请输入使用量" allowClear={true} />
         </Form.Item>
         <Form.Item label="生产厂家" name="manufacturer" rules={[{ required: true, message: '生产厂家为空' }]}>
           <Input placeholder="请输入生产厂家" allowClear={true} />
         </Form.Item>
         <Form.Item
           label="用药日期"
           name="date"
           rules={[{ required: true, message: '用药日期为空' }]}
         >
            <DatePicker format="YYYY-MM-DD" value-Format="YYYY-MM-DD" />
         </Form.Item>
       </Form>
     </Modal>
     </div>
    );
  };

  const TableContainer = () => {
    const columns: ColumnsType<ISheetData> = [
      {
        title: '塘号',
        dataIndex: 'poolNo',
        key: 'poolNo',
        align: 'center',
        fixed: 'left',
        className: 'first-column',
      },
      {
        title: '上报人',
        dataIndex: 'reporter',
        key: 'reporter',
        align: 'center',
      },
      {
        title: '发生日期',
        dataIndex: 'date',
        key: 'date',
        align: 'center',
        render: (value) => formatDate(value),
      },
      {
        title: '药物名称',
        dataIndex: 'drug',
        key: 'drug',
        align: 'center',
      },
      {
        title: '使用量',
        dataIndex: 'dosage',
        key: 'dosage',
        align: 'center',
      },
      {
        title: '生产厂家',
        dataIndex: 'manufacturer',
        key: 'manufacturer',
        align: 'center',
      },
      {
        title: '上报日期',
        dataIndex: 'reportDate',
        key: 'reportDate',
        align: 'center',
        render: (value) => formatDate(value),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        key: 'operation',
        align: 'center',
        render: (_, record: ISheetData) => (
          <Space className="operation">
             <a className="operation-item edit" onClick={() => handleEdit(record)}>
              修改
            </a>
            <Popconfirm title="确认删除该条数据？" onConfirm={() => handleDelete(record)}>
              <a style={{ color: 'red' }}>删除</a>
            </Popconfirm>
          </Space>
        ),
      },
    ];

    function handleDelete(record: ISheetData) {
      // 从record对象中获取poolNo和date
      const { poolNo, date } = record;

  // 发送请求以删除数据
      request.record
      .deleteMedicationRecordData({poolNo, date}).then((res) => {
        if (res.status === 200) {
          // 删除成功后，更新本地状态
        setSheetData((prevData) =>
          prevData.filter((item) => item.poolNo !== poolNo || item.date !== date)
        );
        }
        setShowLoading(false);
      });
      message.success({
        duration: 2,
        content: '删除成功',
      });
    }
    // 此处为修改用药记录
    const layout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
    };   
    function convertDateFormat(dateString) {
      // 假设输入格式为 MM/DD/YYYY
      const parts = dateString.split('/');
      // 转换为 YYYY-MM-DD 格式
      return `${parts[0]}-${parts[1]}-${parts[2]}`;
    }   
    const [form] = Form.useForm();
    const [editModalOpen, setEditModalOpen] = useState(false);
    const [editingRecord, setEditingRecord]: [ISheetData[], any] = useState([]);
    const handleEdit = (record: ISheetData) => {
    setEditModalOpen(true);
    setEditingRecord(record);
    };
    const EditModal = (props: { record: ISheetData}) => {
    const { record } = props;
    function handleEditSubmit() {
      setConfirmLoading(true);
      form.validateFields().then((res) => {
       request.record
        .editMedicationRecordData({poolNo: res.poolNo,
          drug:res.drug,
          dosage: res.dosage,
          manufacturer:res.manufacturer,
          date: res.date,})
        .then((res) => {
          if (res.status === 200) {
            message.success('修改成功', 2);
              // 添加成功后，重新获取数据
            request.record
              .getMedicationRecordData({ date: dateRange })
              .then((res) => {
                const sheetData: ISheetData[] = [];
                for (let i = 0; i < res.data.length; i++) {
                  const item = flatRecordRes(res.data[i]);
                  item['key'] = res.data[i].reportBasic.poolNo + '/' + res.data[i].reportBasic.date + i;
                  sheetData.push(item);
                }
                sheetData.sort((a, b) => {
                  return dayjs(b.date).valueOf() - dayjs(a.date).valueOf(); // 降序排序
                });
                setSheetData(sheetData);
                
              })
          } else message.error('修改失败', 2);
        })
        .finally(() => {
          setConfirmLoading(false);
          setEditModalOpen(false);
        
        });
      });
    }
    return (
    <Modal
        title="修改用药记录"
        open={editModalOpen}
        onOk={handleEditSubmit} // 处理编辑提交的方法
        confirmLoading={confirmLoading}
        cancelText="取消"
        okText="确认修改"
        onCancel={() => {
          setEditModalOpen(false);
        }}
      >
      <Form
            style={{ padding: '20px' }}
            {...layout}
            wrapperCol={{ span: 18 }}
            form={form}
            name="editImmunication"
            autoComplete="off"
            initialValues={{ items: [{}] }}
          >          
        <Form.Item initialValue={record.poolNo} label="塘号" name="poolNo" >
          <Input disabled />
        </Form.Item>
        <Form.Item initialValue={record.reporter} label="上报人" name="userId">
              <Input disabled />
        </Form.Item>
        <Form.Item
        label="用药日期"
        name="date"
        initialValue={convertDateFormat(new Date(record.date).toLocaleString('zh-TW', { year: 'numeric', month: '2-digit', day: '2-digit' }))}
      >
          <Input disabled />
        </Form.Item>
        <Form.Item label="药物名称" initialValue={record.drug} name="drug" rules={[{ required: true, message: '药物名称为空' }]}>
            <Input placeholder="请输入药物名称" allowClear={true} />
        </Form.Item>
        <Form.Item label="使用量" initialValue={record.dosage} name="dosage" rules={[{ required: true, message: '使用量为空' }]}>
            <Input placeholder="请输入使用量" allowClear={true} />
        </Form.Item>
        <Form.Item label="生产厂家" initialValue={record.manufacturer} name="manufacturer" rules={[{ required: true, message: '生产厂家为空' }]}>
            <Input placeholder="请输入生产厂家" allowClear={true} />
        </Form.Item>
      </Form>
    </Modal>
    );
    };
    // 以上为修改用药记录
    return (
      <div className="content-box">
        <Table
          dataSource={sheetData}
          bordered
          pagination={{ pageSize: 1000 }}
          size="small"
          columns={columns}
          id="feed-record-table"
          rowKey={'key'}
          title={() => {
            return `总共匹配到：${sheetData.length}条数据，数据自${dateRange[0]}算起，到${dateRange[1]}。`;
          }}
          loading={showLoading}
        />
        <EditModal record={editingRecord} />
      </div>
    );
  };

  return (
    <div>
      <SearchBar />
      <TableContainer />
    </div>
  );
};
export default MedicationRecord;
function moment(date: any) {
  throw new Error('Function not implemented.');
}

